//
//  companionViewController.m
//  LT
//
//  Created by dllo on 16/5/23.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "companionViewController.h"
#import "companionCollectionViewCell.h"

#import "ZHNetworking.h"
//刷新加载
#import "MJRefresh.h"

static NSString *cellIndentifier = @"cell";

@interface companionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)UICollectionView *myCollectionView;
@property(nonatomic,strong)NSMutableArray *dataArray;


//刷新 //一
@property(nonatomic,assign)NSInteger nextPage;//记录下一页,刷了几页.第一个屏幕还是第二个屏幕
@property(nonatomic,assign)BOOL isUpLoading;//标记上下拉操作,yes上拉

//刷新的时候放的动画图片
@property(nonatomic,strong)NSMutableArray *imageArray;

//读取缓存的数组
@property(nonatomic,strong)NSMutableArray *readArray;




@end

@implementation companionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   // self.view.backgroundColor = [UIColor whiteColor];
    self.dataArray = [NSMutableArray array];
    
    [self read];
  
    //建立用来布局的flowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(120 * WIDTHCELL, 260 * WIDTHCELL);
    // flowLayout.minimumInteritemSpacing = 30;
    flowLayout.minimumLineSpacing = 10 * WIDTHCELL ;
    
    flowLayout.sectionInset = UIEdgeInsetsMake(30 * WIDTHCELL, 10 * WIDTHCELL, 30 * WIDTHCELL, 10 * WIDTHCELL);
    
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    self.myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 10, self.view.frame.size.height) collectionViewLayout:flowLayout];
    
     self.myCollectionView.dk_backgroundColorPicker = DKColorPickerWithRGB(0xFFFFFF,0XD3D3D3);
    [self.view addSubview:self.myCollectionView];
    
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    //注册
    [self.myCollectionView registerClass:[companionCollectionViewCell class] forCellWithReuseIdentifier:cellIndentifier];
    //刷新时的动画显示
    self.imageArray = [NSMutableArray array];
    for (int i = 1; i < 8; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",i]];
        [self.imageArray addObject:image];
    }
 
    //二.下拉刷新
    self.isUpLoading = NO;
    [self addFooter];
    [self addHeader];
    
}


#pragma mark -- 下拉刷新
-(void)addHeader{
    //block中不能使用self.会报错
    __block companionViewController *companionVC = self;
    
    MJRefreshGifHeader *MJHeader = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        //记录页码
        companionVC.nextPage = 1;
        //标记下拉刷新
        companionVC.isUpLoading = NO;
        //请求数据
        [companionVC getData:companionVC.nextPage];
        
    }];
    //普通闲置状态
    [MJHeader setImages:self.imageArray forState:MJRefreshStateIdle];
    //松开就可以进行刷新的状态
    [MJHeader setImages:self.imageArray forState:MJRefreshStatePulling];
    //正在刷新中的状态
    [MJHeader setImages:self.imageArray forState:MJRefreshStateRefreshing];
    
    self.myCollectionView.mj_header = MJHeader;
    
}


#pragma mark -- 上拉加载更多
-(void)addFooter{
    
     __block companionViewController *companionVC = self;
    //添加上拉刷新尾部控件
    
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        //上拉一次自增一次
        companionVC.nextPage ++;
        //标记为上拉操作
        companionVC.isUpLoading = YES;
        //请求数据
      [companionVC getData:companionVC.nextPage];
        
    }];
    
    [footer setImages:self.imageArray forState:MJRefreshStateRefreshing];
    self.myCollectionView.mj_footer = footer;
    
    
}





//item点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"数据维护!" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   
    return self.dataArray.count;
  
}

-(companionCollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    companionCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];

    
    companionModel *model = [self.dataArray objectAtIndex:indexPath.row];
    item.companModel = model;

    item.nameLabel.text = model.title;
    
  //  cell.backgroundColor = [UIColor lightGrayColor];
    return item;
    
}


//读取缓存
-(void)read{
    self.readArray = [NSMutableArray array];
    //取数据从本地plist
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *companionPath = [path stringByAppendingPathComponent:@"companion.plist"];

NSArray *localcompanionArray = [NSArray arrayWithContentsOfFile:companionPath];
    if (localcompanionArray.count != 0) {
        for (NSDictionary *comDic in localcompanionArray ) {
            companionModel *comModel = [[companionModel alloc]init];
            
            [comModel setValuesForKeysWithDictionary:comDic];
            [self.dataArray addObject:comModel];
            
        }

    }


}

//page参数一定要添加,否则就无法出来
-(void)getData:(NSInteger)nextPage{
    
    NSString *string = @"2520";
    NSString *str = @"2";
    NSString *str1 = @"25209.3.1";
    
    
    NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/company/search_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88283798007659&lon=121.539156053574&oauth_token=4ea07b0d41e13f5cb1448a45a3613e45&page=%ld&track_app_channel=App%@Store&track_app_version=6.9.0&track_device_info=iPhone8%@C1&track_deviceid=F417850E-117E-4BF4-AAA6-3AD14E14E3C1&track_os=ios%@&track_user_id=7891151&v=1",(long)nextPage,string,str,str1];
    
[ZHNetworking zhGETWithURL:url parameter:nil succes:^(id result) {
    
    
    NSMutableArray *array = [result objectForKey:@"data"];
    
    
    //*********写入缓存
    //找到Document路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSLog(@"%@",path);//打印的目的是为了确定这个路径对不对
    //拼接一个自己的路径
    NSString *companionPath = [path stringByAppendingPathComponent:@"companion.plist"];
    //写入数据到对应路径的plist文件中
    [array writeToFile:companionPath atomically:YES];

    for (NSDictionary *comDic in array) {
        companionModel *comModel = [[companionModel alloc]init];
        
        [comModel setValuesForKeysWithDictionary:comDic];
        [self.dataArray addObject:comModel];
 
    }
    [self.myCollectionView reloadData];
    
 
} failure:^(NSError *error) {
    
    
}];


}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
